import axios from 'axios'
import store from '@/store'
import { ElMessage } from 'element-plus'
import {
  VERSION,
  MODEL_TEST_VERSION,
  SERVER_TYPE,
  AXIOS_TIMEOUT,

} from '@/constant'

import { switchServerUrl } from "@/utils/index";

axios.interceptors.request.use(config => {
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.reject(error)
})

export default function http(options) {
  let server_url = switchServerUrl()

  let opt = {},
    method = options.method || "post",
    url = options.url,
    data = options.data || {};
  const excelName = options.excelName || "模版"

  if (!options.url) {
    console.error("url参数缺失")
    return;
  }
  if (method == "get") {
    opt = {
      method: method,
      baseURL: "",
      header: { 'Content-Type': 'application/xls' },
      responseType: 'blob',
      url: url.indexOf('//') > -1 ? url : (server_url + url),
      params: data,
      timeout: AXIOS_TIMEOUT,
    }
  }
  else if (method == "post") {
    opt = {
      method: method,
      header: { 'Content-Type': 'application/xls' },
      baseURL: "",
      responseType: 'blob',
      url: url.indexOf('//') > -1 ? url : (server_url + url),
      data: data, //qs.stringify(data)
      timeout: AXIOS_TIMEOUT
    }
  }

  return new Promise((resolve, reject) => {
    axios(opt).then(response => {
      if (!response || !response.data) {
        ElMessage.error("导出失败！");
        return;
      }
      let blob = new Blob([response.data]);//response.data为后端传的流文件
      let downloadFilename = excelName + ".xlsx";//设置导出的文件名
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        //兼容ie浏览器
        window.navigator.msSaveOrOpenBlob(blob, downloadFilename)
      } else {
        //谷歌,火狐等浏览器
        let url = window.URL.createObjectURL(blob);
        let downloadElement = document.createElement("a");
        downloadElement.style.display = "none";
        downloadElement.href = url;
        downloadElement.download = downloadFilename;
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(url);
      }
      ElMessage.success('导出成功！');

    }).catch(err => {
      ElMessage.error("导出失败！");
    })
  })

}